<?php
declare (strict_types = 1);

namespace app\tcp\controller;

use app\BaseController;
use think\facade\Env;
use think\facade\Db;
use app\nizw\Help;
use think\facade\Log;
use app\common\service\BaseService;



class Index extends BaseController
{
    public function index()
    {
        // //登入游戏
        // $data=['game'=>'吃吃碰碰'
    
        // ];
        // return json($data);
    
        // return Help::Inst2()->TestTu();
        // $data = ['name' => 'ThinkPHP'];
        // return $this->fetch('ECharts/index.html');

        Log::error("==========");
        $data=['game'=>'tcp'
    
        ];
        return json($data);
    }
    public function login()
    {
        $username = $this->getParam('username');
        $password = $this->getParam('password');
        $deviceId = $this->getParam('device_id', '');
        $version = $this->getParam('version', '1.0.0');
        
        // 验证参数
        if (empty($username) || empty($password)) {
            return $this->error('用户名和密码不能为空');
        }
        
        try {
            // 用户认证
            $user = $this->authenticateUser($username, $password);
            if (!$user) {
                return $this->error('用户名或密码错误');
            }
            
            // 生成Unity专用token
            $token = $this->generateUnityToken($user['id'], $deviceId);
            
            // 记录登录日志
            $this->logUnityLogin($user['id'], $deviceId, $version);
            
            // 返回Unity格式的响应
            return $this->success([
                'user_id' => $user['id'],
                'username' => $user['username'],
                'nickname' => $user['nickname'],
                'token' => $token,
                'level' => $user['level'],
                'exp' => $user['exp'],
                'server_time' => date('Y-m-d H:i:s')
            ], '登录成功');
            
        } catch (\Exception $e) {
            return $this->error('登录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户游戏数据
     */
    public function getGameData()
    {
        $userId = $this->getParam('user_id');
        
        try {
            $gameData = [
                'score' => 1000,
                'coins' => 5000,
                'items' => [
                    ['id' => 1, 'name' => '武器', 'count' => 3],
                    ['id' => 2, 'name' => '药水', 'count' => 5]
                ],
                'characters' => [
                    ['id' => 1, 'name' => '战士', 'level' => 10],
                    ['id' => 2, 'name' => '法师', 'level' => 8]
                ]
            ];
            
            return $this->success($gameData, '游戏数据获取成功');
            
        } catch (\Exception $e) {
            return $this->error('获取游戏数据失败');
        }
    }
    
    /**
     * 处理Unity心跳
     */
    public function heartbeat()
    {
        $clientInfo = [
            'ip' => $this->clientInfo['ip'],
            'ping' => $this->getParam('ping', ''),
            'timestamp' => time()
        ];
        
        // 更新客户端最后活动时间
        $this->updateClientActivity();
        
        return $this->success(['pong' => 'pong', 'server_time' => date('Y-m-d H:i:s')]);
    }
    
    /**
     * 处理Unity聊天消息
     */
    public function chat()
    {
        $userId = $this->getParam('user_id');
        $content = $this->getParam('content');
        $channel = $this->getParam('channel', 'world');
        
        if (empty($content)) {
            return $this->error('消息内容不能为空');
        }
        
        // 消息过滤
        $filteredContent = $this->filterContent($content);
        
        // 广播聊天消息
        $broadcastData = [
            'from_user' => $userId,
            'from_name' => '玩家' . $userId,
            'content' => $filteredContent,
            'channel' => $channel,
            'timestamp' => time()
        ];
        
        $this->broadcastToUnityClients('chat_message', $broadcastData);
        
        return $this->success([], '消息发送成功');
    }
    
    /**
     * 生成Unity专用token
     */
    private function generateUnityToken($userId, $deviceId)
    {
        $token = md5($userId . $deviceId . time() . uniqid());
        
        // 存储到缓存
        cache('unity_token_' . $token, [
            'user_id' => $userId,
            'device_id' => $deviceId,
            'login_time' => time(),
            'ip' => $this->clientInfo['ip']
        ], 3600 * 24 * 7); // 7天有效期
        
        return $token;
    }
    
    /**
     * 记录Unity登录日志
     */
    private function logUnityLogin($userId, $deviceId, $version)
    {
        $logData = [
            'user_id' => $userId,
            'device_id' => $deviceId,
            'version' => $version,
            'ip' => $this->clientInfo['ip'],
            'login_time' => date('Y-m-d H:i:s')
        ];
        
        // 写入日志文件或数据库
        file_put_contents(
            runtime_path('log/unity_login.log'),
            json_encode($logData, JSON_UNESCAPED_UNICODE) . PHP_EOL,
            FILE_APPEND
        );
    }
    
    /**
     * 内容过滤
     */
    private function filterContent($content)
    {
        // 简单的敏感词过滤
        $sensitiveWords = ['不良词1', '不良词2'];
        return str_replace($sensitiveWords, '***', $content);
    }
    
    /**
     * 向所有Unity客户端广播消息
     */
    private function broadcastToUnityClients($action, $data)
    {
        // 这里需要实现广播逻辑
        // 可以使用连接管理器广播给所有连接的Unity客户端
    }
}
